//
//  TagListView.swift
//  shop
//
//  Created by chen on 2025/5/17.
//

import SwiftUI

struct TagListView: View {
    
    let tags: [String]
    let spacing: CGFloat = 8 // 标签之间的间距
    
    @ObservedObject var router: Router
    
    var body: some View {
        GeometryReader { geometry in
            self.generateContent(in: geometry)
        }
    }
    
    private func generateContent(in g: GeometryProxy) -> some View {
        var width = CGFloat.zero
        var height = CGFloat.zero
        
        return ZStack(alignment: .topLeading) {
            ForEach(Array(tags.enumerated()), id: \.element) { index,tag in
                Button {
                    router.to(.searchResult(keyWord: tag))
                } label: {
                    TagView(text: tag, index: index)
                        .padding(.horizontal, 4)
                        .padding(.vertical, 2)
                        .alignmentGuide(.leading) { d in
                            if abs(width - d.width) > g.size.width {
                                width = 0
                                height -= d.height + spacing
                            }
                            let result = width
                            if tag == tags.last {
                                width = 0
                            } else {
                                width -= d.width + spacing
                            }
                            return result
                        }
                        .alignmentGuide(.top) { _ in
                            let result = height
                            if tag == tags.last {
                                height = 0
                            }
                            return result
                        }
                }
                .buttonStyle(PlainButtonStyle())
            }
        }
    }
}

// 单个标签视图
struct TagView: View {
    
    let text: String
    let index: Int
    
    var body: some View {
        Text(text)
            .padding(.horizontal, 10)
            .padding(.vertical, 5)
            .font(.system(size: 13))
            .foregroundStyle(index <= 2 ? .red : .black)
            .background(Color.tagBg)
            .cornerRadius(15)
    }
}

#Preview{
    let tags = ["SwiftUI", "iOS", "Swift", "编程", "开发", "标签", "自动换行", "示例"]
    TagListView(tags: tags, router: Router.shared)
}
